package Servlet;

import entity.User;
import org.json.JSONObject;
import utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author Su
 * @Date 2025/4/30 22:50
 * @Version 1.0 （版本号）
 */
@WebServlet("/api/like")
public class LikeServlet extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");

        //数据库连接和预处理语句对象初始化为null。
        Connection conn = null;
        PreparedStatement pstmt = null;
        //构建json响应对象
        JSONObject responseJson = new JSONObject();
        try {

            //将字符串类型的文章ID转换为整数  ////req.getParameter("articleId")从请求参数获取文章id
            int articleId = Integer.parseInt(req.getParameter("articleId"));
            HttpSession session = req.getSession(false);
            if (session == null) {
                responseJson.put("code", 401);
                responseJson.put("message", "未登录");
                resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }
            //从会话中获取已登录的用户对象
            User user = (User) session.getAttribute("user");
            ///数据库操作
            conn = DBUtil.getConnection();//获取数据库连接

            // 检查现有记录
            pstmt = conn.prepareStatement(
                    "SELECT id, status FROM article_likes " +
                            "WHERE article_id = ? AND user_id = ? FOR UPDATE");
            //FOR UPDATE 加锁语句，防止并发修改导致数据不一致
            //锁定用户的点赞记录(防止并发修改)
            //检查当前状态(status)
            //切换状态(1变0或0变1)
            //更新数据库

            //setint 设置预处理语句参数值
            pstmt.setInt(1, articleId);
            pstmt.setInt(2, user.getUserId());

            ResultSet rs = pstmt.executeQuery();//执行查询并返回结果集




            //点赞状态切换
            if (rs.next()) {//rs.next()：检查是否存在该用户的点赞记录
                // 存在记录，切换状态
                int currentStatus = rs.getInt("status");
                //如果当前状态为1(已点赞)则改为0(取消点赞)，反之亦然

                //三元运算
                int newStatus = currentStatus == 1 ? 0 : 1;

                pstmt = conn.prepareStatement(//NOW() 是 MySQL 函数，返回当前日期时间，//记录最后修改时间
                        "UPDATE article_likes SET status = ?, updated_at = NOW() " +
                                "WHERE id = ?");
                pstmt.setInt(1, newStatus);
                pstmt.setInt(2, rs.getInt("id"));
                pstmt.executeUpdate();

            } else {
                // 新增点赞记录
                pstmt = conn.prepareStatement(
                        "INSERT INTO article_likes (article_id, user_id, status) " +
                                "VALUES (?, ?, 1)");
                pstmt.setInt(1, articleId);
                pstmt.setInt(2, user.getUserId());
                pstmt.executeUpdate();
            }

            // 返回最新状态
            responseJson.put("code", 200);
            responseJson.put("message", "请求成功");

        } catch (SQLException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            resp.getWriter().print(responseJson.toString());
            DBUtil.closeConnection(conn);
        }
    }//*****Redis缓存点赞状态和计数，减轻数据库压力
    //******短时间内很多人同时点赞，引入缓存层 如Redis 减轻数据库压力

}